package com.xiaoq.manager.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaoq.coms.util.DigestUtil;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.manager.entity.MerchantMgrEntity;
import com.xiaoq.manager.exception.ManagerAlreadyExistException;
import com.xiaoq.manager.repository.IMerchantMgrRepository;
import com.xiaoq.manager.service.IManagerAccountService;
import com.xiaoq.users.entity.UserTermDeviceEntity;
import com.xiaoq.users.service.TencentIMService;
import com.xiaoq.users.service.TencentRequestVo;
import com.xiaoq.users.service.TencentResponseVo;
import com.xiaoq.users.service.exception.AuthenFailException;

@Component
public class ManagerAccountServiceImpl implements IManagerAccountService {

	@Autowired
	private IMerchantMgrRepository merchantRep;
	
	@Autowired
	private IdGenerator idGenerator;
	
	@Autowired
    private TencentIMService tencentIMService;

	private static final Logger LOG = LoggerFactory.getLogger(ManagerAccountServiceImpl.class);

	@Override
	public MerchantMgrEntity createByCellphoneNumber(MerchantMgrEntity merchant) {
		if (merchantRep.findByMobile(merchant.getMobile()) != null) {
			throw new ManagerAlreadyExistException();
		}
		merchant.setSalt(idGenerator.nextId());
		entryptPassword(merchant, merchant.getPasswd());
		
		//向腾讯IM注册一个用户
        TencentRequestVo tencenRequestVo = new TencentRequestVo();
        tencenRequestVo.setIdentifier(merchant.getId());
        tencenRequestVo.setNick(merchant.getName());
        tencenRequestVo.setFaceUrl(merchant.getLogoUrl());
        TencentResponseVo tencentResponse = tencentIMService.tencentAccount(tencenRequestVo);
        
        
		return merchantRep.save(merchant);
	}
	public MerchantMgrEntity loginByMobileAndPasswd(String mobile, String passwd, UserTermDeviceEntity termDevice) {
		MerchantMgrEntity merchantMgrInDB;
		merchantMgrInDB = merchantRep.findByMobile(mobile);
		if (merchantMgrInDB == null) {
			throw new AuthenFailException();
		}
		if (!isValidPassword(merchantMgrInDB, passwd)) {
			throw new AuthenFailException();
		}
		if (termDevice != null) {
			updateLastLoginedDeviceInfoInUserEntityAndMemberEntity(merchantMgrInDB, termDevice);
		}
		//向腾讯IM注册一个用户
        TencentRequestVo tencenRequestVo = new TencentRequestVo();
        tencenRequestVo.setIdentifier(merchantMgrInDB.getId());
        tencenRequestVo.setNick(merchantMgrInDB.getName());
        tencenRequestVo.setFaceUrl(merchantMgrInDB.getLogoUrl());
        TencentResponseVo tencentResponse = tencentIMService.tencentAccount(tencenRequestVo);
		
		return merchantRep.save(merchantMgrInDB);

	}

	/**
	 * 这个就是每次登陆更新设备信息
	 * @param userInDB
	 * @param termDevice
	 */
	private void updateLastLoginedDeviceInfoInUserEntityAndMemberEntity(MerchantMgrEntity merchantMgrInDB,
			UserTermDeviceEntity termDevice) {
		UserTermDeviceEntity termDeviceInDB = merchantMgrInDB.getTermDevice();
		long curTime = System.currentTimeMillis();
		if (termDeviceInDB == null) {
			termDeviceInDB = new UserTermDeviceEntity();
			termDeviceInDB.setId(idGenerator.nextId());
			termDeviceInDB.setCreatedAt(curTime);
			merchantMgrInDB.setTermDevice(termDeviceInDB);
		}
		BeanUtils.copyProperties(termDevice, termDeviceInDB);
		termDeviceInDB.setUpdatedAt(curTime);

	}

	
	private boolean isValidPassword(MerchantMgrEntity merchant, String password) {
		String entryptPassword = DigestUtil.md5(password + "{" + merchant.getSalt() + "}");
		return merchant.getPasswd().equals(entryptPassword);
	}

	private void entryptPassword(MerchantMgrEntity merchant, String password) {
		merchant.setPasswd(DigestUtil.md5(password + "{" + merchant.getSalt() + "}"));
	}

	@Override
	public MerchantMgrEntity findById(String id) {
		
		return merchantRep.findById(id);
	}

	@Override
	public MerchantMgrEntity addMerchantMgr(MerchantMgrEntity merchant) {
		if (merchantRep.findByMobile(merchant.getMobile()) != null) {
			throw new ManagerAlreadyExistException("手机号已经存在！");
		}
		merchant.setSalt(idGenerator.nextId());
		entryptPassword(merchant, merchant.getPasswd());
		merchantRep.save(merchant);
		
		//向腾讯IM注册一个用户
        TencentRequestVo tencenRequestVo = new TencentRequestVo();
        tencenRequestVo.setIdentifier(merchant.getId());
        tencenRequestVo.setNick(merchant.getName());
        tencenRequestVo.setFaceUrl(merchant.getLogoUrl());
        TencentResponseVo tencentResponse = tencentIMService.tencentAccount(tencenRequestVo);
        
		return merchantRep.save(merchant);
	}

	@Override
	public boolean resetPassword(String mobile, String password) {
		MerchantMgrEntity merchantMgrInDB;
		merchantMgrInDB = merchantRep.findByMobile(mobile);
		if (merchantMgrInDB == null) {
			throw new RuntimeException("管理员不存在");
		}
		entryptPassword(merchantMgrInDB, password);
		//向腾讯IM注册一个用户
        TencentRequestVo tencenRequestVo = new TencentRequestVo();
        tencenRequestVo.setIdentifier(merchantMgrInDB.getId());
        tencenRequestVo.setNick(merchantMgrInDB.getName());
        tencenRequestVo.setFaceUrl(merchantMgrInDB.getLogoUrl());
        TencentResponseVo tencentResponse = tencentIMService.tencentAccount(tencenRequestVo);
		merchantRep.save(merchantMgrInDB);
		return true;
	}
	
	@Override
	public boolean updateMgr(String mobile, String oldPwd, String newPwd, String name, String logoUrl) {
		MerchantMgrEntity merchantMgrInDB;
		merchantMgrInDB = merchantRep.findByMobile(mobile);
		if(oldPwd!=null){
			if (merchantMgrInDB == null) {
				throw new RuntimeException("管理员不存在");
			}
			if (!isValidPassword(merchantMgrInDB, oldPwd)) {
				throw new RuntimeException("密码和账号不匹配请查询后重新修改");
			}
			if (newPwd != null) {
				entryptPassword(merchantMgrInDB, newPwd);
				//向腾讯IM注册一个用户
		        TencentRequestVo tencenRequestVo = new TencentRequestVo();
		        tencenRequestVo.setIdentifier(merchantMgrInDB.getId());
		        tencenRequestVo.setNick(merchantMgrInDB.getName());
		        tencenRequestVo.setFaceUrl(merchantMgrInDB.getLogoUrl());
		        TencentResponseVo tencentResponse = tencentIMService.tencentAccount(tencenRequestVo);
				

			}else{
				throw new RuntimeException("新密码不能为空！");
			}
		}
		if(StringUtils.isNotEmpty(name)){
			merchantMgrInDB.setName(name);
		}
		if(StringUtils.isNotEmpty(logoUrl)){
			merchantMgrInDB.setLogoUrl(logoUrl);
		}
		MerchantMgrEntity merchantMgr = merchantRep.save(merchantMgrInDB);
		if(merchantMgr!=null){
			return true;
		}
		return false;
	}

	@Override
	public boolean updataMerchant(MerchantMgrEntity merchant) {
		String id = merchant.getId();
		MerchantMgrEntity merchantMgrInDB = merchantRep.findById(id);
		String mobile = merchant.getMobile();
		if(!mobile.equals(merchantMgrInDB.getMobile())){
			if (merchantRep.findByMobile(mobile) != null) {
				throw new ManagerAlreadyExistException("手机号已经存在！");
			}
		}
		merchantMgrInDB.setMobile(merchant.getMobile());
		merchantMgrInDB.setName(merchant.getName());
		merchantMgrInDB.setContact(merchant.getContact());
		merchantMgrInDB.setMgrRoles(merchant.getMgrRoles());
		merchantMgrInDB.setMenuList(merchant.getMenuList());
		merchantMgrInDB.setRoleId(merchant.getRoleId());
		String password = merchant.getPasswd();
		String reg = "(?i)^(?!([a-z]*|\\d*)$)[a-z\\d]{6,20}$";
		if(StringUtils.isNotEmpty(password)&&password.matches(reg)){
			entryptPassword(merchantMgrInDB, password);
			//向腾讯IM注册一个用户
	        TencentRequestVo tencenRequestVo = new TencentRequestVo();
	        tencenRequestVo.setIdentifier(merchantMgrInDB.getId());
	        tencenRequestVo.setNick(merchantMgrInDB.getName());
	        tencenRequestVo.setFaceUrl(merchantMgrInDB.getLogoUrl());
	        TencentResponseVo tencentResponse = tencentIMService.tencentAccount(tencenRequestVo);
			

		}
		
		return merchantRep.updateMerchantMgr(merchantMgrInDB);
	}

	@Override
	public MerchantMgrEntity createByEmail(MerchantMgrEntity merchant) {
		if (merchantRep.findByMobile(merchant.getMobile()) != null) {
			throw new RuntimeException("手机号已经存在！");
		}
		if (merchantRep.findByEmail(merchant.getEmail()) != null) {
			throw new RuntimeException("邮箱已经存在！");
		}
		merchant.setSalt(idGenerator.nextId());
		entryptPassword(merchant, merchant.getPasswd());
		//向腾讯IM注册一个用户
        TencentRequestVo tencenRequestVo = new TencentRequestVo();
        tencenRequestVo.setIdentifier(merchant.getId());
        tencenRequestVo.setNick(merchant.getName());
        tencenRequestVo.setFaceUrl(merchant.getLogoUrl());
        TencentResponseVo tencentResponse = tencentIMService.tencentAccount(tencenRequestVo);

		return merchantRep.save(merchant);
	}

	@Override
	public MerchantMgrEntity loginByEmail(String email, String passwd, UserTermDeviceEntity termDevice) {
		MerchantMgrEntity merchantMgrInDB;
		merchantMgrInDB = merchantRep.findByEmail(email);
		if (merchantMgrInDB == null) {
			throw new RuntimeException("邮箱代表的用户不存在！");
		}
		if (!isValidPassword(merchantMgrInDB, passwd)) {
			throw new RuntimeException("邮箱或则密码出错！");
		}
		if (termDevice != null) {
			updateLastLoginedDeviceInfoInUserEntityAndMemberEntity(merchantMgrInDB, termDevice);
		}
		
		return merchantRep.save(merchantMgrInDB);
	}
	@Override
	public MerchantMgrEntity findByEmail(String email) {
		return merchantRep.findByEmail(email);
	}
	@Override
	public List<MerchantMgrEntity> findByRoleId(String roleId,String shopId) {
		return merchantRep.findByRoleId(roleId,shopId);
	}
	
	

}
